package com.fram.controller.admin.botany;

import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fram.bean.admin.botany.request.BotanyBasicMessageRequest;
import com.fram.bean.sys.PageBean;
import com.fram.bean.sys.ResponseMsg;
import com.fram.common.canstant.BotanyConstantMethod;
import com.fram.common.canstant.ErrCode;
import com.fram.common.exception.ProAffairException;
import com.fram.common.exception.ProException;
import com.fram.common.util.PublicMethod;
import com.fram.common.util.apiversion.ApiVersion;
import com.fram.common.util.base.BaseAdminController;
import com.fram.common.util.file.FileUtils;
import com.fram.common.util.json.JSONTools;
import com.fram.entity.BotanyBasicMessage;
import com.fram.entity.BotanyDetailMessage;
import com.fram.service.admin.botany.BotanyMessageService;

/**
 * @作者： 陳曉鬆 @时间： 2020年7月2日 - 下午3:59:59 @description：-> 植物信息
 */
@RestController
@RequestMapping("/admin/botany/{version}/message")
public class BotanyMessageController extends BaseAdminController {

	private static Logger LOG = LoggerFactory.getLogger(BotanyMessageController.class);

	@Resource(name = "botanyMessageService")
	private BotanyMessageService botanyMessageService;

	@ApiVersion(1.0)
	@RequestMapping(value = "/add")
	private ResponseMsg add(@RequestBody BotanyBasicMessage request) {
		ResponseMsg msg = ResponseMsg.returnBeanBuild();
		try {
			request.setAdminUserId(getAdminUserId());
			botanyMessageService.insertBotanyBasicMessage(request);
		} catch (ProException e) {
			LOG.error("-植物信息-add出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
		} catch (ProAffairException e) {
			LOG.error("-植物信息-add出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
		} catch (Exception e) {
			LOG.error("-植物信息-add异常->{},{}", msg.getSessionId(), PublicMethod.printErrorTrace(e));
			msg.setReturnCode(ErrCode.ERR.getReturnCode()).setReturnMsg(ErrCode.ERR.getReturnMsg());
		}
		return msg;
	}

	@ApiVersion(1.0)
	@RequestMapping(value = "/update")
	private ResponseMsg update(@RequestBody BotanyBasicMessage request) {
		ResponseMsg msg = ResponseMsg.returnBeanBuild();
		try {
			botanyMessageService.updateBotanyBasicMessage(request);
		} catch (ProAffairException e) {
			LOG.error("-植物信息-update出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
		} catch (Exception e) {
			LOG.error("-植物信息-update异常->{},{}", msg.getSessionId(), PublicMethod.printErrorTrace(e));
			msg.setReturnCode(ErrCode.ERR.getReturnCode()).setReturnMsg(ErrCode.ERR.getReturnMsg());
		}
		return msg;
	}

	@ApiVersion(1.0)
	@RequestMapping(value = "/basic/list")
	private ResponseMsg basiclist(@RequestBody PageBean<BotanyBasicMessageRequest> request) {
		ResponseMsg msg = ResponseMsg.returnBeanBuild();
		try {
			msg.setData(botanyMessageService.queryBasicMessage(request));
		} catch (ProAffairException e) {
			LOG.error("-植物信息-basic/list出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
		} catch (Exception e) {
			LOG.error("-植物信息-basic/list异常->{},{}", msg.getSessionId(), PublicMethod.printErrorTrace(e));
			msg.setReturnCode(ErrCode.ERR.getReturnCode()).setReturnMsg(ErrCode.ERR.getReturnMsg());
		}
		return msg;
	}

	@ApiVersion(1.0)
	@RequestMapping(value = "/detail/add")
	private ResponseMsg detailadd(@RequestBody BotanyDetailMessage request) {
		ResponseMsg msg = ResponseMsg.returnBeanBuild();
		try {
			request.setAdminUserId(getAdminUserId());
			msg.setData(botanyMessageService.insertBotanyDetailMessage(request));
		} catch (ProException e) {
			LOG.error("-植物信息-detailadd出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
		} catch (ProAffairException e) {
			LOG.error("-植物信息-detailadd出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
		} catch (Exception e) {
			LOG.error("-植物信息-detailadd异常->{},{}", msg.getSessionId(), PublicMethod.printErrorTrace(e));
			msg.setReturnCode(ErrCode.ERR.getReturnCode()).setReturnMsg(ErrCode.ERR.getReturnMsg());
		}
		return msg;
	}

	/**
	 * @作者：陳曉鬆 @时间：2020年7月10日 下午3:17:34 @版本：V1.0 @description：-> 上传文件图片
	 */
	@ApiVersion(1.0)
	@PostMapping("upload/image")
	public ResponseMsg uploadChatImage(@RequestParam("file") MultipartFile[] files, Long basicId, Long detailId) {
		ResponseMsg msg = ResponseMsg.returnBeanBuild();
		try {
			msg.setData(botanyMessageService.uploadImage(basicId, detailId, files != null ? Arrays.asList(files) : null));
		} catch (ProAffairException e) {
			LOG.error("-植物信息-上传图片出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
		} catch (Exception e) {
			LOG.error("-植物信息-上传图片异常->{},{}", msg.getSessionId(), PublicMethod.printErrorTrace(e));
			msg.setReturnCode(ErrCode.ERR.getReturnCode()).setReturnMsg(ErrCode.ERR.getReturnMsg());
		}
		return msg;
	}

	@ApiVersion(1.0)
	@GetMapping(value = "/image/read/{fileName}")
	public void getImage(@PathVariable String fileName, HttpServletResponse response) {
		ResponseMsg msg = ResponseMsg.returnBeanBuild();
		OutputStream os = null;
		try {
			String[] str = fileName.split("_");
			// 读取图片
			BufferedImage image = ImageIO.read(new FileInputStream(BotanyConstantMethod.getPath(Long.valueOf(str[0]), Long.valueOf(str[1])) + fileName));
			response.setContentType("image/" + fileName.substring(fileName.indexOf(".") + 1));
			os = response.getOutputStream();
			if (image != null) {
				ImageIO.write(image, fileName.substring(fileName.indexOf(".") + 1), os);
			}
		} catch (ProAffairException e) {
			LOG.error("-植物信息-上传图片出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
			PublicMethod.outPrint(response, JSONTools.obj2json(msg), "json");
		} catch (Exception e) {
			LOG.error("获取图片异常{}", e.getMessage());
			msg.setReturnCode(ErrCode.ERR.getReturnCode()).setReturnMsg(ErrCode.ERR.getReturnMsg());
			PublicMethod.outPrint(response, JSONTools.obj2json(msg), "json");
		} finally {
			if (os != null) {
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
					msg.setReturnCode(ErrCode.ERR.getReturnCode()).setReturnMsg(ErrCode.ERR.getReturnMsg());
					PublicMethod.outPrint(response, JSONTools.obj2json(msg), "json");
				}
			}
		}
	}

	@ApiVersion(1.0)
	@RequestMapping("down")
	public void down(HttpServletResponse response, Long basicId) {
		try {
			// 设置信息给客户端不解析
			String type = new MimetypesFileTypeMap().getContentType(".zip");
			// 设置contenttype，即告诉客户端所发送的数据属于什么类型
			response.setHeader("Content-type", type);
			String filePath = botanyMessageService.zipDownPath(basicId);
			// 设置编码
			String decode = new String(filePath.substring(filePath.lastIndexOf("/") + 1).getBytes("utf-8"), "iso-8859-1");
			// 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
			response.setHeader("Content-Disposition", "attachment;filename=" + decode);
			FileUtils.download(filePath, response);
			FileUtils.deleteFile(filePath);
		} catch (ProAffairException e) {
			LOG.error("-植物信息-下载出错->{},{}", e.getErrorCode(), e.getErrorMsg());
		} catch (Exception e) {
			LOG.error("-植物信息-下载异常->{}", PublicMethod.printErrorTrace(e));
		}
	}

	@ApiVersion(1.0)
	@RequestMapping(value = "/data")
	private ResponseMsg data(@RequestBody(required = false) String str) {
		ResponseMsg msg = ResponseMsg.returnBeanBuild();
		try {
			System.out.println(str);
			// } catch (ProException e) {
			// LOG.error("-植物信息-detailadd出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			// msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
			// } catch (ProAffairException e) {
			// LOG.error("-植物信息-detailadd出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			// msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
		} catch (Exception e) {
			LOG.error("-植物信息-detailadd异常->{},{}", msg.getSessionId(), PublicMethod.printErrorTrace(e));
			msg.setReturnCode(ErrCode.ERR.getReturnCode()).setReturnMsg(ErrCode.ERR.getReturnMsg());
		}
		return msg;
	}

}
